package com.dong8.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.dong8.R;
import com.dong8.resp.RespGym;
import com.dong8.sys.Constants;
import com.dong8.sys.MyApp;
import com.dong8.type.Gym;
import com.dong8.util.ImageLoaderHelper;
import com.dong8.util.MgqDataHandler;
import com.dong8.util.MgqRestClient;
import com.dong8.util.PreferencesUtils;
import com.dong8.util.UtilAPI;
import com.loopj.android.http.RequestParams;

@SuppressLint("HandlerLeak")
public class RecommendGymActivity extends Activity implements OnClickListener {
	MyAdapter m_adapter;
	private List<Gym> m_array_list = null;

	int mType = 0;
	String mKey = "";
	
	private LocationClient mLocationClient = null;
	public BDLocation mLocation = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recommend_gym);
/*
		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.PULL_UP_TO_REFRESH);
		ptrlvHeadlineNews.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				getData(false);
			}
		});
*/
		if(((MyApp)getApplicationContext()).mCurrentGym != null)
		{
			ImageButton button = (ImageButton)findViewById(R.id.ibBack);
			button.setBackgroundResource(R.drawable.btn_back);
			button.setImageBitmap(null);
			button.setOnClickListener(this);
		}
		
		ListView listview =  (ListView)findViewById(R.id.listview);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
			{
				if(((MyApp)getApplicationContext()).mFinishActivity != null)
				{
					((MyApp)getApplicationContext()).mFinishActivity.finish();
					((MyApp)getApplicationContext()).mFinishActivity = null;
				}
				
				PreferencesUtils.putString(RecommendGymActivity.this,"user_gym", JSON.toJSONString(m_array_list.get(arg2)));
				((MyApp)getApplicationContext()).mCurrentGym = m_array_list.get(arg2);
				startActivity(new Intent(RecommendGymActivity.this, MainActivity.class));
				finish();
			}
		});

		m_adapter = new MyAdapter();
		listview.setAdapter(m_adapter);
		
		findViewById(R.id.titleRight).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) 
			{
				startActivityForResult(new Intent(RecommendGymActivity.this, MyCityListActivity.class), 100);
			}
		});

		final EditText textview = (EditText) findViewById(R.id.tv_title);
		textview.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				InputMethodManager imm = (InputMethodManager) arg0.getContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
				if (imm.isActive())
					imm.hideSoftInputFromWindow(arg0.getApplicationWindowToken(), 0);

				mKey = ((EditText) findViewById(R.id.tv_title)).getText().toString();
				getData(true);
				((EditText) findViewById(R.id.tv_title)).setText("");
				return true;
			}
		});

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) 
			{
				findViewById(R.id.loc).setVisibility(View.GONE);
				
				final Dialog dialog = new Dialog(RecommendGymActivity.this,R.style.dialog);
				dialog.setContentView(R.layout.dialog); 
				dialog.setCancelable(true);
				
				((Button)dialog.findViewById(R.id.confirm)).setText("选择城市");
				dialog.findViewById(R.id.confirm).setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						startActivityForResult(new Intent(RecommendGymActivity.this, MyCityListActivity.class), 100);
						dialog.dismiss();
					}
				});
				dialog.findViewById(R.id.cancel).setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						dialog.dismiss();
					}
				});
				
				((TextView)dialog.findViewById(R.id.msg)).setText("定位失败，是否通过城市选择场馆？");
				dialog.show();
				
				super.handleMessage(msg);
			}
		};

		final Timer timer = new Timer();
		timer.schedule(new TimerTask() 
		{
			@Override
			public void run() 
			{
				if (mLocation == null)
				{
					handler.sendEmptyMessage(0);
				}
			}
		}, 5000);
		
		final BDLocationListener listener = new BDLocationListener()
		{
			@Override
			public void onReceiveLocation(BDLocation location) 
			{
				if (location == null)
					return;
				
				mLocation = location;
				mLocationClient.unRegisterLocationListener(this);
				mLocationClient.stop();
				timer.cancel();
				
				findViewById(R.id.loc).setVisibility(View.GONE);
				getData(true);
			}

			public void onReceivePoi(BDLocation poiLocation) 
			{
			}
		};
		
		mLocationClient = new LocationClient(this);
		mLocationClient.registerLocationListener(listener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(600000);
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		if(resultCode == 100)
		{
			getCityData(intent.getExtras().getString("code"));
		}
		
		super.onActivityResult(requestCode, resultCode, intent);
	}

	class MyAdapter extends BaseAdapter {
		public int getCount() {
			if (m_array_list == null)
				return 0;
			return m_array_list.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) 
		{
			ViewHolder holder = null; 
			if (convertView == null) 
			{ 
				holder = new  ViewHolder();
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = mInflater.inflate(R.layout.item_gym, null);
				
				holder.distance = ((TextView) convertView.findViewById(R.id.distance));
				holder.title = ((TextView) convertView.findViewById(R.id.title));
				holder.price = ((TextView) convertView.findViewById(R.id.price));
				holder.img = ((ImageView) convertView.findViewById(R.id.img));
				
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag(); 
			}
			
			Gym gym = m_array_list.get(position);

			if(mLocation != null)
			{
				double meter = UtilAPI.gps2m(mLocation.getLatitude(),mLocation.getLongitude(), gym.lat, gym.lng);
				holder.title.setText(gym.clubName);
				holder.distance.setText(String.format("%.3f千米", meter));	
			}
			
			holder.price.setText(gym.price);

			ImageLoaderHelper.displayImage(R.drawable.default_img_small, holder.img, gym.img);
			return convertView;
		}
	}
	
	public double gps2m(double lat_a, double lng_a, double lat_b, double lng_b) 
	{
		double radLat1 = (lat_a * Math.PI / 180.0);
		double radLat2 = (lat_b * Math.PI / 180.0);
		double a = radLat1 - radLat2;
		double b = (lng_a - lng_b) * Math.PI / 180.0;
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378137.0;
		s = Math.round(s * 10000) / 10000;
		s = s/1000;
		return s;
	}

	public final class ViewHolder 
	{
		public TextView title;
		public TextView distance;
		public TextView price;
		public ImageView img;
	}

	private void getData(boolean show) {
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
//				((PullToRefreshListView) findViewById(R.id.listview)).onRefreshComplete();

				super.onSuccess(response);
				RespGym ruser = JSON.parseObject(response, RespGym.class);
				if (ruser.code.equals("0")) 
				{
					m_array_list = ruser.data;
					m_adapter.notifyDataSetChanged();
					
					if(m_array_list.size() == 0) findViewById(R.id.tvNodata).setVisibility(View.VISIBLE);
					else findViewById(R.id.tvNodata).setVisibility(View.GONE);
				} 
				else 
				{

				}
			}

			public void onFailure(Throwable ble) {
//				((PullToRefreshListView) findViewById(R.id.listview)).onRefreshComplete();
			}
		};

		// lat=104.43144&lng=34.789567&key=贺龙

		RequestParams params = new RequestParams();
		params.put("lat", mLocation.getLatitude());
		params.put("lng", mLocation.getLongitude());
		params.put("type", mType);
		try {
			params.put("key", URLEncoder.encode(mKey, "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constants.CLUB_DISTANCE, params, loginHandler);
	}
	
	private void getCityData(String code)
	{
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) 
		{
			@Override
			public void onSuccess(String response) 
			{
				super.onSuccess(response);
				RespGym ruser = JSON.parseObject(response, RespGym.class);
				if (ruser.code.equals("0")) 
				{
					m_array_list = ruser.data;
				}
				else 
				{
					m_array_list = null;
				}
				
				m_adapter.notifyDataSetChanged();
				if(m_array_list == null || m_array_list.size() == 0) findViewById(R.id.tvNodata).setVisibility(View.VISIBLE);
				else findViewById(R.id.tvNodata).setVisibility(View.GONE);
			}

			public void onFailure(Throwable ble) 
			{
			}
		};

		// lat=104.43144&lng=34.789567&key=贺龙

		RequestParams params = new RequestParams();
		params.put("data", code);
		MgqRestClient.get(Constants.CLUB_CITY, params, loginHandler);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.filter:
			mType = 1 - mType;
			if (mType == 0)
				((Button) arg0).setSelected(false);
			else
				((Button) arg0).setSelected(true);
			getData(true);
			break;
			
		case R.id.ibBack:
			finish();
			break;
		}
	}
}
